package com.pearadmin.common.tools.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;
import java.util.Map;

/**
 * 使用auth0处理token
 */
public class Auth0JwtUtil {

    private static final String SECRET = "secret";
    private static final Algorithm algorithm = Algorithm.HMAC256(SECRET);

    /**
     * 验证token
     *
     * @param token token
     * @return 返回解析出来的map对象
     */
    public static Map<String, Claim> verify(String token) throws JWTVerificationException {
        try {
            DecodedJWT jwt = null;
            JWTVerifier verifier = JWT.require(algorithm).build();
            jwt = verifier.verify(token);
            return jwt.getClaims();
        } catch (TokenExpiredException tokenExpiredException) {
            throw new JWTVerificationException("token过期", tokenExpiredException);
        } catch (JWTVerificationException exception) {
            throw new JWTVerificationException("解析失败", exception);
        }


    }

    /**
     * 生成token
     *
     * @param claims 需要被加入到token中的对象
     * @return token
     */
    public static String create(Map<String, String> claims) {
        JWTCreator.Builder builder = JWT.create();
        claims.forEach(builder::withClaim);
        return builder
                .withExpiresAt(DateUtils.addDays(new Date(), 7))
                .withIssuedAt(new Date())
                .sign(algorithm);

    }
}
